package com.lightheart.sphr.xiaobinggan.timeselection.uitls

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import com.lightheart.sphr.xiaobinggan.timeselection.listener.TimerListener

/**
 *    Author :hongliang
 *    E-mail : 13717858152@163.com
 *    Date   : 2021/1/1811:37 AM
 *    Desc   :
 *    Version: 1.0.0
 */
class MyCountDownTimer(private var mMillisHas: Long) {

    /**
     * Millis since epoch when alarm should stop.
     */
    private var mMillisInFuture: Long = 30 * 1000L

    /**
     * The interval in millis that the user receives callbacks
     */
    private var mCountdownInterval: Long = 1000L

    private var mStopTimeInFuture: Long = 0

    /**
     * boolean representing if the timer was cancelled
     */
    private var mCancelled = false
    private var listener: TimerListener? = null

    fun setHasTime(mMillisHas: Long) {
        this.mMillisHas = mMillisHas
    }

    fun setTimerListener(listener: TimerListener) {
        this.listener = listener
    }

    /**
     * Cancel the countdown.
     */
    @Synchronized
    fun cancel() {
        mCancelled = true
        mHandler.removeMessages(MSG)
    }

    /**
     * Start the countdown.
     */
    @Synchronized
    fun start(): MyCountDownTimer {
        mCancelled = false
        if (mMillisInFuture <= 0) {
            listener?.onFinish()
            return this
        }
        mStopTimeInFuture = if (mMillisHas <= 0) {
            SystemClock.elapsedRealtime() + mMillisInFuture
        } else {
            SystemClock.elapsedRealtime() + mMillisInFuture - mMillisHas
        }
        mHandler.sendMessage(mHandler.obtainMessage(MSG))
        return this
    }


    private val MSG = 1


    private val mHandler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
//            synchronized(this@MyCountDownTimer) {
            if (mCancelled) {
                return
            }
            val millisLeft =
                    mStopTimeInFuture - SystemClock.elapsedRealtime()
            if (millisLeft <= 0) {
                mMillisHas = 0
                TimerManager.instance.stopTimer(0)
                listener?.onFinish()
            } else {
                val lastTickStart = SystemClock.elapsedRealtime()
                listener?.onTick((30 - millisLeft / 1000L).toInt())
                // take into account user's onTick taking time to execute
                val lastTickDuration =
                        SystemClock.elapsedRealtime() - lastTickStart
                var delay: Long
                if (millisLeft < mCountdownInterval) {
                    // just delay until done
                    delay = millisLeft - lastTickDuration

                    // special case: user's onTick took more than interval to
                    // complete, trigger onFinish without delay
                    if (delay < 0) delay = 0
                } else {
                    delay = mCountdownInterval - lastTickDuration
                    // special case: user's onTick took more than interval to
                    // complete, skip to next interval
                    while (delay < 0) delay += mCountdownInterval
                }
                sendMessageDelayed(obtainMessage(MSG), delay)
//                }
            }
        }
    }
}
